package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import com.atguigu.gulimall.product.vo.Catalog2Vo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redisson;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 查出所有Category组装成Tree
     * @return
     */
    @Override
    public List<CategoryEntity> listWithTree() {
        // 1. 查出所有Category
        List<CategoryEntity> entities = baseMapper.selectList(null);
        // 2. 组装成Tree
        // 2.1 找到所有1级分类
        List<CategoryEntity> level1Menu = entities.stream()
                .filter(e -> e.getParentCid() == 0)
                .map(menu -> {
                    menu.setChildren(getChildren(menu, entities));
                    return menu;
                })
                .sorted(Comparator.comparingInt(cate -> cate.getSort() == null ? 0 : cate.getSort()))
                .collect(Collectors.toList());

        return level1Menu;
    }

    @Override
    public void removeMenuByIds(List<Long> catIds) {
        // TODO 检查菜单下是否有商品

        baseMapper.deleteBatchIds(catIds);
    }

    /**
     * 找到catalogId的完整路径
     * @param catalogId
     * @return
     */
    @Override
    public Long[] findCatalogPath(Long catalogId) {
        List<Long> path = new ArrayList<Long>();
        findParentPath(catalogId, path);

        Long[] array = new Long[path.size()];
        return path.toArray(array);
    }

    /**
     * 级联更新
     * @param category
     */
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        // 其他
        categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());

    }

    @Cacheable(value = {"category"}, key = "#root.method.name")
    @Override
    public List<CategoryEntity> getLevel1Categories() {
        System.out.println("Query Level1Categories From DB");
        long startTime = System.currentTimeMillis();
        List<CategoryEntity> categoryEntities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        long endTime = System.currentTimeMillis();
        System.out.println("CategoryServiceImpl.getLevel1Categories() 耗时：" + ( endTime - startTime ) + "ms");
        return categoryEntities;
    }

    @Override
    public Map<String, List<Catalog2Vo>> getCatalogJson() {
        String cacheCatalogJson = redisTemplate.opsForValue().get("catalogJSON");
        if (StringUtils.isEmpty(cacheCatalogJson)) {
            Map<String, List<Catalog2Vo>> catalogJsonFromDB = getCatalogJsonFromDB();
//            redisTemplate.opsForValue().set("catalogJSON", JSON.toJSONString(catalogJsonFromDB));
            return catalogJsonFromDB;
        } else {
            Map<String, List<Catalog2Vo>> cacheObj = JSON.parseObject(cacheCatalogJson, new TypeReference<Map<String, List<Catalog2Vo>>>() {});
            return cacheObj;
        }

    }

    public Map<String, List<Catalog2Vo>> getCatalogJsonFromDBWithRedissonLock() {
        RLock lock = redisson.getLock("catalogJson-lock");

        Map<String, List<Catalog2Vo>> catalogJsonFromDB = null;
        try {
            catalogJsonFromDB = getCatalogJsonFromDB();
        } finally {
            lock.unlock();
        }

        return catalogJsonFromDB;
    }

    public Map<String, List<Catalog2Vo>> getCatalogJsonFromDBWithLocalLock() {
        synchronized (this) {
            String cacheCatalogJson = redisTemplate.opsForValue().get("catalogJSON");
            if (!StringUtils.isEmpty(cacheCatalogJson)) {
                Map<String, List<Catalog2Vo>> cacheObj = JSON.parseObject(cacheCatalogJson, new TypeReference<Map<String, List<Catalog2Vo>>>() {});
                return cacheObj;
            }

            List<CategoryEntity> all = baseMapper.selectList(null);
            // 查一级分类
            List<CategoryEntity> level1Categories = getParentCid(all, 0L);

            // 封装数据
            Map<String, List<Catalog2Vo>> cates = level1Categories.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
                // 查1级分类下的2级分类
                List<CategoryEntity> level2List = getParentCid(all, v.getCatId());
                List<Catalog2Vo> Catalog2Vos = null;
                if (level2List != null) {
                    Catalog2Vos = level2List.stream().map(l2 -> {
                        Catalog2Vo Catalog2Vo = new Catalog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                        // 查二级下的3级
                        List<CategoryEntity> level3List = getParentCid(all, l2.getCatId());

                        if (level3List != null) {
                            List<Catalog2Vo.Catalog3Vo> collect = level3List.stream().map(l3 -> {
                                Catalog2Vo.Catalog3Vo catalog3Vo = new Catalog2Vo.Catalog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                                return catalog3Vo;
                            }).collect(Collectors.toList());
                            Catalog2Vo.setCatalog3List(collect);
                        }

                        return Catalog2Vo;
                    }).collect(Collectors.toList());
                }
                return Catalog2Vos;
            }));

            redisTemplate.opsForValue().set("catalogJSON", JSON.toJSONString(cates));

            return cates;
        }
    }

    /**
     * 从数据库查询并封装数据
     * @return
     */
    public Map<String, List<Catalog2Vo>> getCatalogJsonFromDB() {
        String cacheCatalogJson = redisTemplate.opsForValue().get("catalogJSON");
        if (!StringUtils.isEmpty(cacheCatalogJson)) {
            Map<String, List<Catalog2Vo>> catalogJsonFromDB = getCatalogJsonFromDB();
            redisTemplate.opsForValue().set("catalogJSON", JSON.toJSONString(catalogJsonFromDB));
            return catalogJsonFromDB;
        }

        List<CategoryEntity> all = baseMapper.selectList(null);
        // 查一级分类
        List<CategoryEntity> level1Categories = getParentCid(all, 0L);

        // 封装数据
        Map<String, List<Catalog2Vo>> cates = level1Categories.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            // 查1级分类下的2级分类
            List<CategoryEntity> level2List = getParentCid(all, v.getCatId());
            List<Catalog2Vo> Catalog2Vos = null;
            if (level2List != null) {
                Catalog2Vos = level2List.stream().map(l2 -> {
                    Catalog2Vo Catalog2Vo = new Catalog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    // 查二级下的3级
                    List<CategoryEntity> level3List = getParentCid(all, l2.getCatId());

                    if (level3List != null) {
                        List<Catalog2Vo.Catalog3Vo> collect = level3List.stream().map(l3 -> {
                            Catalog2Vo.Catalog3Vo catalog3Vo = new Catalog2Vo.Catalog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return catalog3Vo;
                        }).collect(Collectors.toList());
                        Catalog2Vo.setCatalog3List(collect);
                    }

                    return Catalog2Vo;
                }).collect(Collectors.toList());
            }
            return Catalog2Vos;
        }));

        redisTemplate.opsForValue().set("catalogJSON", JSON.toJSONString(cates));

        return cates;
    }

    private List<CategoryEntity> getParentCid(List<CategoryEntity> all, Long catId) {
        return all.stream().filter(e -> e.getParentCid() == catId).collect(Collectors.toList());
    }

    private void findParentPath(Long catalogId, List<Long> path) {
        CategoryEntity byId = this.getById(catalogId);
        if (byId.getParentCid() != null && byId.getParentCid() != 0) {
            findParentPath(byId.getParentCid(), path);
        }
        path.add(byId.getCatId());
    }

    /**
     * 递归查找菜单的子菜单
     * @param root
     * @param all
     * @return
     */
    private List<CategoryEntity> getChildren(CategoryEntity root, List<CategoryEntity> all) {
        return all.stream()
                .filter(e -> e.getParentCid().equals(root.getCatId()))
                .map(e -> {
                    // 1.找到子菜单
                    e.setChildren(getChildren(e, all));
                    return e;
                })
                .sorted(Comparator.comparingInt(cate -> cate.getSort() == null ? 0 : cate.getSort()))
                .collect(Collectors.toList());
    }

}